import { baseModule } from "@/base/module";
import { LazyLoader } from "@sapi-game/gameComponent/common/lazyLoader";
import { GamePlayer } from "@sapi-game/gamePlayer/gamePlayer";
import { PlayerGroup } from "@sapi-game/gamePlayer/playerGroup";
import { CubeRegion } from "@sapi-game/gameRegion/gameRegion";
import { Game } from "@sapi-game/main";
import { DimensionIds } from "@sapi-game/utils/vanila-data";
import { PixelParty } from "../game";
import { PixelPartyStarter } from "./starter";
import { pixelPartyMaps } from "../map";

export class PixelPartyBackState extends baseModule.State {
    readonly players = new PlayerGroup(GamePlayer);
    readonly region = new CubeRegion(
        DimensionIds.Overworld,
        { x: 193, y: -38, z: -154 },
        { x: 97, y: -64, z: -243 }
    );

    override onEnter(): void {
        this.addComponent(LazyLoader, {
            onLoad: this.onLoad.bind(this),
            onUnload: this.onUnload.bind(this),
            pos: { x: 183, y: -54, z: -198 },
            dimensionId: DimensionIds.Overworld,
        });
    }

    onLoad(loader: LazyLoader) {
        loader.addComponent(PixelPartyStarter);
    }

    onUnload() {
        this.players.clear();
    }

    start() {
        const players = this.region.getPlayersInRegion();
        Game.manager.startGame(PixelParty, {
            players: players,
            map: pixelPartyMaps.classic,
        });
        this.getComponent(LazyLoader).reload();
    }
}
